package com.itheima.mongo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.itheima.dbservice.UserInfoServiceApi;
import com.itheima.mongoservice.FriendServiceApi;
import com.itheima.mongoservice.RecommendServiceApi;
import com.itheima.mongoservice.UserLikeServiceApi;
import com.itheima.pojo.UserInfo;
import com.itheima.pojo.mongo.Friend;
import com.itheima.pojo.mongo.RecommendUser;
import com.itheima.pojo.mongo.UserLike;
import com.itheima.vo.FriendPageList;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@DubboService
public class UserLikeServiceApiImpl implements UserLikeServiceApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private FriendServiceApi friendServiceApi;
    @Autowired
    private RecommendServiceApi recommendServiceApi;
    @DubboReference
    private UserInfoServiceApi userInfoServiceApi;


    @Override
    public List<UserLike> getUserInfos(Long uid) {
        Query query = Query.query(Criteria.where("userId").is(uid));
        return mongoTemplate.find(query, UserLike.class);
    }

    @Override
    public boolean getIsLikeExist(Long uid, Long id, boolean isLike) {
        Query query = Query.query(Criteria.where("userId").is(uid).and("likeUserId").is(id).and("isLike").is(isLike));
        return mongoTemplate.exists(query, UserLike.class);
    }

    @Override
    public void addLikeInfo(UserLike userLike) {
        mongoTemplate.save(userLike);
    }

    @Override
    public List<UserLike> getLikeUserInfos(Long uid) {
        boolean flag = true;
        Query query = Query.query(Criteria.where("likeUserId").is(uid)
                .and("isLike").is(flag));
        return mongoTemplate.find(query, UserLike.class);
    }



    /**
     * 添加粉丝喜欢
     * @param uid
     * @param id
     */
    @Override
    public void addUserLike(Long uid, Long id) {
        //构造条件
        Query query = Query.query(Criteria.where("likeUserId").is(uid).and("userId").is(id));
        //获取数据
        UserLike userLike = mongoTemplate.findOne(query, UserLike.class);
        //设置喜欢状态
        userLike.setLike(true);
        //将数据存储进userlike数据表中
        mongoTemplate.save(userLike);
        //在userLike列表汇也要添加数据
        //查询该数据是否存在
        Query query1 = Query.query(Criteria.where("likeUserId").is(id).and("userId").is(uid));
        UserLike like = mongoTemplate.findOne(query1, UserLike.class);
        if (ObjectUtil.isNull(like)){
            like = new UserLike();
            like.setLike(true);
            like.setUserId(uid);
            like.setLikeUserId(id);
            like.setCreated(System.currentTimeMillis());
            like.setUpdated(System.currentTimeMillis());
        }
        like.setLike(true);
        like.setUpdated(System.currentTimeMillis());
        mongoTemplate.save(like);


        //将数据添加至friend表中
        //查询该id是否存在
        Query query2 = Query.query(Criteria.where("userId").is(id).and("friendId").is(uid));
        Friend friend = mongoTemplate.findOne(query2, Friend.class);
        //判断
        if (ObjectUtil.isNull(friend)){
            Friend friend1 = new Friend();
            friend1.setCreated(System.currentTimeMillis());
            friend1.setUserId(uid);
            friend1.setFriendId(id);
            mongoTemplate.save(friend1);
            Friend friend2 = new Friend();
            friend2.setCreated(System.currentTimeMillis());
            friend2.setUserId(id);
            friend2.setFriendId(uid);
            mongoTemplate.save(friend2);
        }
    }

    /**
     * 喜欢 - 取消
     * @param uid
     * @param id
     */
    @Override
    public void deleteUserLike(Long uid, Long id) {
        //构造条件
        Query query = Query.query(Criteria.where("userId").is(uid).and("likeUserId").is(id));
        //删除userlike字段
        mongoTemplate.remove(query,UserLike.class);
        //同时将粉丝表中字段变为false
//        Query query1 = Query.query(Criteria.where("userId").is(id).and("likeUserId").is(uid));
//        UserLike userLike = mongoTemplate.findOne(query1, UserLike.class);
//        userLike.setLike(false);
//        mongoTemplate.save(userLike);
    }

    //获取互相喜欢，喜欢，粉丝数据
    @Override
    public Map getTotalCount(Long uid) {
        //构造条件查询喜欢数目
        Query likeQuery = Query.query(Criteria.where("isLike").is(true).and("userId").is(uid));
        Integer likeCount = mongoTemplate.find(likeQuery, UserLike.class).size();
        //构造条件查询粉丝数目
        Query fanQuery = Query.query(Criteria.where("likeUserId").is(uid).and("isLike").is(true));
        Integer fanCount = mongoTemplate.find(fanQuery, UserLike.class).size();
        //查询相互喜欢数目
        Integer eachCount = friendServiceApi.getEachCount(uid);
        //创建集合存储数据
        Map map=new HashMap();
        map.put("eachLoveCount",eachCount);
        map.put("loveCount",likeCount);
        map.put("fanCount",fanCount);

        return map;
    }



    //相互喜欢
    @Override
    public List<FriendPageList> eachPageList(Long uid, Integer page, Integer pagesize, String nickname) {
        //构造条件
        Query query = new Query(Criteria.where("userId").is(uid))
                .skip((page-1)*pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.asc("created")));
        //查询结果
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        //判断结果
        if (ObjectUtil.isNull(friends)){
            return null;
        }
        //获取id集合
        List<Long> userIds = CollUtil.getFieldValues(friends, "friendId", Long.class);
        //获取用户详细信息
        List<UserInfo> userInfos = userInfoServiceApi.selectByIds(userIds, nickname);
        List<FriendPageList> eachPageList = new ArrayList<>();
        //遍历集合
        for (UserInfo userInfo : userInfos) {
            FriendPageList friendPageList = new FriendPageList();
            //获取用户id
            Long id = userInfo.getId();
            //获取推荐用户查询缘分值
            RecommendUser recommendUser = recommendServiceApi.findPageList(uid, id);
            //
            //将数据封装
            BeanUtil.copyProperties(userInfo,friendPageList);
            friendPageList.setAlreadyLove(true);//好友默认喜欢
            friendPageList.setMatchRate(ObjectUtil.isNull(recommendUser) ? 50 : Convert.toInt(recommendUser.getScore()));
            eachPageList.add(friendPageList);
        }
        return eachPageList;
    }

    //粉丝分页
    @Override
    public List<FriendPageList> fanPageList(Long uid, Integer page, Integer pagesize,String nickname) {
        //构造条件
        Query query = new Query(Criteria.where("likeUserId").is(uid).and("isLike").is(true))
                .skip((page-1)*pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.asc("created")));
        //查询结果
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        //获取ids集合
        List<Long> userIds = CollUtil.getFieldValues(userLikeList, "userId", Long.class);
        //查询用户信息集合
        List<UserInfo> userInfos = userInfoServiceApi.selectByIds(userIds, nickname);
        List<FriendPageList> eachPageList = new ArrayList<>();
        //遍历集合
        for (UserInfo userInfo : userInfos) {
            FriendPageList friendPageList = new FriendPageList();
            //获取id
            Long id = userInfo.getId();
            //查询推荐以获取推荐值
            RecommendUser recommendUser = recommendServiceApi.findPageList(uid, id);
            //查看是否喜欢
            UserLike userLike = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(uid).and("likeUserId").is(id)), UserLike.class);
            //将数据封装
            BeanUtil.copyProperties(userInfo,friendPageList);
            friendPageList.setAlreadyLove(ObjectUtil.isNull(userLike) ? false : userLike.isLike());
            //若无推荐信息则设置50
            friendPageList.setMatchRate(ObjectUtil.isNull(recommendUser) ? 50 : Convert.toInt(recommendUser.getScore()));
            eachPageList.add(friendPageList);
        }
        return eachPageList;
    }


    //喜欢分页
    @Override
    public List<FriendPageList> likePageList(Long uid, Integer page, Integer pagesize, String nickname) {
        //构造条件
        Query query = new Query(Criteria.where("userId").is(uid).and("isLike").is(true))
                .skip((page-1)*pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.asc("created")));
        //查询结果
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        //获取其id集合
        List<Long> likeUserIds = CollUtil.getFieldValues(userLikes, "likeUserId", Long.class);
        //获取用户详细信息
        List<UserInfo> userInfos = userInfoServiceApi.selectByIds(likeUserIds, nickname);
        //判断结果
        if (ObjectUtil.isNull(userLikes)){
            return null;
        }
        List<FriendPageList> eachPageList = new ArrayList<>();
        //遍历用户详细信息
        for (UserInfo userInfo : userInfos) {
            FriendPageList friendPageList = new FriendPageList();
            //获取用户id
            Long id = userInfo.getId();
            //查询推荐以获取推荐值
            RecommendUser recommendUser = recommendServiceApi.findPageList(uid, id);
            //查看是否喜欢这里为true
            // 将数据封装
            BeanUtil.copyProperties(userInfo,friendPageList);
            friendPageList.setAlreadyLove(true);
            friendPageList.setMatchRate(ObjectUtil.isNull(recommendUser)?50:Convert.toInt(recommendUser.getScore()));
            eachPageList.add(friendPageList);
        }
        return eachPageList;
    }
/*
    //相互喜欢
    @Override
    public List<FriendPageList> eachPageList(Long uid, Integer page, Integer pagesize,String nickname) {
        //构造条件
        Query query = new Query(Criteria.where("userId").is(uid))
                .skip((page-1)*pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.asc("created")));
        //查询结果
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        //判断结果
        if (ObjectUtil.isNull(friends)){
            return null;
        }
        List<FriendPageList> eachPageList = new ArrayList<>();
        for (Friend friend : friends) {
            FriendPageList friendPageList = new FriendPageList();
            Long friendId = friend.getFriendId();
            //调用接口查询用户缘分值
            RecommendUser recommendUser = recommendServiceApi.findPageList(uid, friendId);
            //调用接口查询用户信息
            UserInfo userInfo = userInfoServiceApi.getUserInfoById(friendId);
            //将数据封装
            BeanUtil.copyProperties(userInfo,friendPageList);
            friendPageList.setAlreadyLove(true);//好友默认喜欢
            friendPageList.setMatchRate(ObjectUtil.isNull(recommendUser) ? 50 : Convert.toInt(recommendUser.getScore()));
            eachPageList.add(friendPageList);
        }
        return eachPageList;
    }

    //粉丝分页
    @Override
    public List<FriendPageList> fanPageList(Long uid, Integer page, Integer pagesize,String nickname) {
        //构造条件
        Query query = new Query(Criteria.where("likeUserId").is(uid))
                .skip((page-1)*pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.asc("created")));;
        //查询结果
        List<UserLike> fans = mongoTemplate.find(query, UserLike.class);
        //判断结果
        if (ObjectUtil.isNull(fans)){
            return null;
        }
        List<FriendPageList> eachPageList = new ArrayList<>();
        for (UserLike fan : fans) {
            FriendPageList friendPageList = new FriendPageList();
            Long fanId = fan.getUserId();
            //调用接口查询用户缘分值
            RecommendUser recommendUser = recommendServiceApi.findPageList(uid, fanId);
//            if (ObjectUtil.isNull(recommendUser)){
//                continue;
//            }
            //调用接口查询用户信息
            UserInfo userInfo = userInfoServiceApi.getUserInfoById(fanId);
            //查看是否喜欢
            UserLike userLike = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(fanId).and("likeUserId").is(uid)), UserLike.class);
            //将数据封装
            BeanUtil.copyProperties(userInfo,friendPageList);
            friendPageList.setAlreadyLove(userLike.isLike());
            friendPageList.setMatchRate(ObjectUtil.isNull(recommendUser) ? 50 : Convert.toInt(recommendUser.getScore()));
            eachPageList.add(friendPageList);
        }
        return eachPageList;
    }

    //喜欢分页
    @Override
    public List<FriendPageList> likePageList(Long uid, Integer page, Integer pagesize,String nickname) {
        //构造条件
        Query query = new Query(Criteria.where("userId").is(uid).and("isLike").is(true))
                .skip((page-1)*pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.asc("created")));;
        //查询结果
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        //判断结果
        if (ObjectUtil.isNull(userLikes)){
            return null;
        }
        List<FriendPageList> eachPageList = new ArrayList<>();
        for (UserLike userLike : userLikes) {
            FriendPageList friendPageList = new FriendPageList();
            Long userLikeId = userLike.getLikeUserId();
            //调用接口查询用户缘分值
            RecommendUser recommendUser = recommendServiceApi.findPageList(uid, userLikeId);
//            if (ObjectUtil.isNull(recommendUser)){
//                continue;
//            }
            //调用接口查询用户信息
            UserInfo userInfo = userInfoServiceApi.getUserInfoById(userLikeId);
            //查看是否喜欢
            UserLike userLike1 = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(uid).and("likeUserId").is(userLikeId)), UserLike.class);
            //将数据封装
            BeanUtil.copyProperties(userInfo,friendPageList);
            friendPageList.setAlreadyLove(userLike1.isLike());
            friendPageList.setMatchRate(ObjectUtil.isNull(recommendUser) ? 50 : Convert.toInt(recommendUser.getScore()));
            eachPageList.add(friendPageList);
        }
        return eachPageList;
    }*/

    @Override
    public void updateIsLike(Long uid, Long id, boolean b) {
        Query query = Query.query(Criteria.where("userId").is(uid)
                .and("likeUserId").is(id));
        UserLike userLike = mongoTemplate.findOne(query, UserLike.class);
        if (ObjectUtil.isNull(userLike)){
            return;
        }
        userLike.setLike(b);
        mongoTemplate.save(userLike);
    }

}
